package a04_字符串;

import java.util.Arrays;

/**
 * <p>
 * a04_翻转字符串里的单词复习5
 * </p>
 *
 * @author flyduck
 * @since 2025/2/25
 */
public class a04_翻转字符串里的单词复习5 {

    public static void main(String[] args) {
        a04_翻转字符串里的单词复习5 test = new a04_翻转字符串里的单词复习5();
        System.out.println(test.reverseWords("  this  is  a good  sample  "));
    }

    public String reverseWords(String s) {
        char[] oldChar = s.toCharArray();
        char[] newChar = removeAllSpaces(oldChar);
        reverse(newChar,0,newChar.length-1);
        reverseEachWord(newChar);
        return new String(newChar);
    }

    private void reverseEachWord(char[] newChar) {
        int leftIdx = 0;
        int rightIdx = 0;

        while (rightIdx < newChar.length){
            if(rightIdx == newChar.length - 1 || newChar[rightIdx+1] == ' '){
                reverse(newChar, leftIdx, rightIdx);
                rightIdx = rightIdx + 2;
                leftIdx = rightIdx;
            }else {
                rightIdx++;
            }
        }
    }

    private void reverse(char[] newChar, int leftIdx, int rightIdx) {
        while (leftIdx < rightIdx){
            char temp = newChar[leftIdx];
            newChar[leftIdx] = newChar[rightIdx];
            newChar[rightIdx] = temp;
            leftIdx++;
            rightIdx--;
        }
    }

    private char[] removeAllSpaces(char[] oldChar) {
        int slowIdx = 0;
        int fastIdx = 0;
        while (fastIdx < oldChar.length){
            if(oldChar[fastIdx] != ' '){
                if(slowIdx != 0){
                    oldChar[slowIdx] = ' ';
                    slowIdx++;
                }
                while (fastIdx < oldChar.length && oldChar[fastIdx] != ' '){
                    oldChar[slowIdx] = oldChar[fastIdx];
                    slowIdx++;
                    fastIdx++;
                }
            }else {
                fastIdx++;
            }
        }
        return Arrays.copyOfRange(oldChar, 0, slowIdx);
    }
}
